﻿using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml.Linq;

namespace GDM.Hogar.Soporte.Helpers
{
    public static class XmlHelper
    {
        public static string GetXml<T>(T objects)
        {
            var stream = new MemoryStream();
            var sr = new StreamReader(stream);

            var serializer = new DataContractSerializer(typeof(T));

            serializer.WriteObject(stream, objects);
            stream.Position = 0;

            string parms = sr.ReadToEnd();
            parms = RemoveAllNamespaces(parms);
            stream.Close();

            return parms;
        }

        public static string RemoveAllNamespaces(string xmlDocument)
        {
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));
            return xmlDocumentWithoutNs.ToString();
        }

        public static XElement RemoveAllNamespaces(XElement xmlDocument)
        {
            if (!xmlDocument.HasElements)
            {
                var localXElement = new XElement(xmlDocument.Name.LocalName) { Value = xmlDocument.Value };
                return localXElement;
            }

            return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(RemoveAllNamespaces));
        }
    }
}